package logkit

import (
	"fmt"
	"testing"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"
	"github.com/xuelang-group/suanpan-appconnector/pkg/suanpan_log"
)

func TestLogkitEmit(t *testing.T) {
	ti := time.Now()
	a := make([]string, 0)
	RegisterHandler(func(info *LogInfo) error {
		assert.Equal(t, info.Level, "WARN")
		assert.Equal(t, info.Data.Node, "n4")
		a = append(a, info.Title)
		return nil
	})

	err := EmitLog(logrus.WarnLevel, ti, "t2", "n4")
	assert.NoError(t, err)
	//sleep a while to whit handler finished
	//not use channel because avoid blocking forever
	time.Sleep(100 * time.Millisecond)
	assert.Equal(t, a[0], "t2")

	err = EmitLog(logrus.TraceLevel, ti, "t", "t")
	assert.Equal(t, err != nil, true)

	//CloseLogKit()
}

func TestWithoutLogkitField(t *testing.T) {
	log := logrus.New()
	hook := suanpan_log.NewSuanpanLogWithFunc("logkit", logrus.InfoLevel, true, LogkitFireFunc)
	log.AddHook(hook)

	a := make([]string, 0)
	RegisterHandler(func(info *LogInfo) error {
		fmt.Println("into test register handler")
		//no node id
		assert.Equal(t, info.Data.Node, "")
		assert.Equal(t, info.Title, "testemm")
		a = append(a, info.Title)
		return nil
	})

	log.Error("testemm")
	//sleep a while to whit handler finished
	//not use channel because avoid blocking forever
	time.Sleep(100 * time.Millisecond)
	assert.Equal(t, a[0], "testemm")

	//not active handler
	log.Debug("terstdbg")
	//sleep a while to whit handler finished
	//not use channel because avoid blocking forever
	time.Sleep(100 * time.Millisecond)
	assert.Equal(t, len(a), 1)
}

func TestWithLogkitField(t *testing.T) {
	log := logrus.New()
	hook := suanpan_log.NewSuanpanLogWithFunc("logkit", logrus.InfoLevel, false, LogkitFireFunc)
	log.AddHook(hook)
	aa := make([]string, 0)
	RegisterHandler(func(info *LogInfo) error {
		fmt.Println("into test register handler")
		//no node id
		assert.Equal(t, info.Data.Node, "")
		aa = append(aa, info.Title)
		return nil
	})
	log.WithField("logkit", true).Info("testarr1")
	//sleep a while to whit handler finished
	//not use channel because avoid blocking forever
	time.Sleep(100 * time.Millisecond)
	//with field append
	assert.Equal(t, aa[0], "testarr1{\"logkit\":true}")
	assert.Equal(t, len(aa), 1)

	log.Info("testarr2")
	//sleep a while to whit handler finished
	//not use channel because avoid blocking forever
	time.Sleep(100 * time.Millisecond)
	fmt.Println(aa)
	assert.Equal(t, len(aa), 1)
}
